﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Net;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Collections;
using System.Data.OleDb;
using System.Threading;
using System.Deployment;
using System.Deployment.Application;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.IO.Ports;

namespace CateringManager
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public static string ComPort = string.Empty;   //
        public static string BaudRate = string.Empty;   //
        public static string DataBits = string.Empty;   //
        public static string cParity = string.Empty;   //
        public static string cStopBits = string.Empty;   //
        public static string RecvType = string.Empty;   //
        public static string managerID = string.Empty;
        public static string managerName = string.Empty;
        public static int managerClasss = 0;
        public static int temp = 0;
        public static int readerSet = 0;
        public static string prevCardId = "테스트전상태입니다";
        ComboControl combCt = new ComboControl();


        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'dataSet1.view_customer_card' table. You can move, or remove it, as needed.
            this.view_customer_cardTableAdapter.Fill(this.dataSet1.view_customer_card);

            CheckForShortcut();
            
            if (managerClasss == 0)
            {
                panelMain.Visible = false;
                panelLogin.Visible = true;
            }
            else
            {
                panelMain.Visible = true;
                panelLogin.Visible = false;

                // TODO: This line of code loads data into the 'dataSet1.customer_card' table. You can move, or remove it, as needed.
                this.customer_cardTableAdapter.FillByCustomerIdx(this.dataSet1.customer_card, 0);
                this.managerTableAdapter.FillByDelChk(this.dataSet1.manager, "N");
                this.cardregistTableAdapter.FillByDelChk(this.dataSet1.cardregist, "N");
                this.productTableAdapter.FillByDelChk(this.dataSet1.product, "N");
                this.companyTableAdapter.FillByDelChk(this.dataSet1.company, "N");
                this.salesTableAdapter.FillByDelChk(this.dataSet1.sales, "N");
                this.salesTableAdapter.FillByDelChk(this.dataSet1.sales, "N");
                this.customerTableAdapter.FillByDelchk(this.dataSet1.customer, "N");
                DataSet1.customerDataTable cdt = new DataSet1.customerDataTable();
                customerTableAdapter.FillByCompanyIdx(cdt, 0);
                this.customerDataGridView.DataSource = cdt;
 
                FileInfo exefileinfo = new FileInfo(Application.ExecutablePath);
                string path = exefileinfo.Directory.FullName.ToString();  //프로그램 실행되고 있는데 path 가져오기
                Assembly asm = Assembly.LoadFrom(path + @"\CateringManager.exe");
                AssemblyName name = asm.GetName();
                this.Text = "식당회원관리 V" + name.Version.ToString();

                path = exefileinfo.Directory.FullName.ToString();  //프로그램 실행되고 있는데 path 가져오기
                string fileName = @"\config.ini";  //파일명

                string sDirPath = @"C:\\Program Files\\KIMJH\\CateringManager";
                DirectoryInfo di = new DirectoryInfo(sDirPath);
                if (di.Exists == false)
                {
                    di.Create();
                }
                string filePath = sDirPath + fileName;   //ini 파일 경로 
                FileInfo fi = new FileInfo(filePath);
                if (fi.Exists == false) fi.Create();

                iniUtil ini = new iniUtil(filePath);   // 만들어 놓았던 iniUtil 객체 생성(생성자 인자로 파일경로 정보 넘겨줌)

                ComPort = ini.GetIniValue("Catering", "ComPort");  //
                if (ComPort == "") ComPort = "COM1";
                BaudRate = ini.GetIniValue("Catering", "BaudRate");  //
                if (BaudRate == "") BaudRate = "9600";
                DataBits = ini.GetIniValue("Catering", "DataBits");  //
                if (DataBits == "") DataBits = "8";
                cParity = ini.GetIniValue("Catering", "cParity");  //
                if (cParity == "") cParity = Parity.None.ToString();
                cStopBits = ini.GetIniValue("Catering", "cStopBits");  //
                if (cStopBits == "") cStopBits = StopBits.One.ToString();
                RecvType = ini.GetIniValue("Catering", "RecvType");  //
                if (RecvType == "") RecvType = "Dec";

                // Initialize Serial Port
                serialPort1.BaudRate = Convert.ToInt32(BaudRate);
                serialPort1.DataBits = Convert.ToInt32(DataBits);
                serialPort1.Parity = Parity.None;
                serialPort1.StopBits = StopBits.One;
                serialPort1.PortName = ComPort;
                try
                {
                    serialPort1.Open();
                    toolStripStatusLabel2.Text = "시리얼 포트 오픈";
                    toolStripMenuItemSerialState.CheckState = CheckState.Checked;
                    toolStripMenuItemSerialState.Text = "연결끊기";
                    MessageBox.Show("카드 리더리 사용을 위한 준비가 되었습니다! \n\n초기화를 위해 카드를 두세번 접촉해서 데이터를 확인해 주세요!");
                }
                catch
                {
                    MessageBox.Show("해당 포트를 열지 못했습니다. 환경 설정을 확인하세요.");
                    toolStripMenuItemSerialState.CheckState = CheckState.Unchecked;
                    toolStripMenuItemSerialState.Text = "연결";
                    return;
                }

                /// <summary>
                /// 공급사 콤포박스 초기화
                /// </summary>  
                DataTable comboDt = new DataTable();
                comboDt.Columns.Add("Item");
                comboDt.Columns.Add("Value");
                comboDt.Rows.Add("없음", "0");
                DataSet1.companyDataTable dt = companyTableAdapter.GetDataByDelChk("N");
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        comboDt.Rows.Add(row["coname"].ToString(), row["idx"].ToString());
                    }
                }
                foreach (DataRow row in comboDt.Rows)
                {
                    combCt.AddComboItem(ref comboBoxConame, row["Value"].ToString(), row["Item"].ToString());
                }
                combCt.SelectComboBox(ref comboBoxConame, "0");

                /// <summary>
                /// 매출 상품 콤포박스 초기화
                /// </summary>  
                DataTable comboDt2 = new DataTable();
                comboDt2.Columns.Add("Item");
                comboDt2.Columns.Add("Value");
                comboDt2.Rows.Add("기타", "0");
                DataSet1.productDataTable dt2 = productTableAdapter.GetDataByDelChk("N");
                if (dt2.Rows.Count > 0)
                {
                    foreach (DataRow row in dt2.Rows)
                    {
                        comboDt2.Rows.Add(row["pname"].ToString(), row["idx"].ToString());
                    }
                }
                foreach (DataRow row in comboDt2.Rows)
                {
                    combCt.AddComboItem(ref comboBoxproductName, row["Value"].ToString(), row["Item"].ToString());
                }
                combCt.SelectComboBox(ref comboBoxproductName, "0");


                /// <summary>
                /// 매출 상품 콤포박스 초기화
                /// </summary>  
                DataTable comboDt3 = new DataTable();
                comboDt3.Columns.Add("Item");
                comboDt3.Columns.Add("Value");
                comboDt3.Rows.Add("무명씨", "0");
                DataSet1.customerDataTable dt3 = customerTableAdapter.GetDataByDelchk("N");
                if (dt2.Rows.Count > 0)
                {
                    foreach (DataRow row in dt3.Rows)
                    {
                        comboDt3.Rows.Add(row["cname"].ToString(), row["idx"].ToString());
                    }
                }
                foreach (DataRow row in comboDt3.Rows)
                {
                    combCt.AddComboItem(ref comboBoxSalesCname, row["Value"].ToString(), row["Item"].ToString());
                }
                combCt.SelectComboBox(ref comboBoxSalesCname, "0");
                


                combCt.AddComboItem(ref mlassComboBox, "1", "직원");
                combCt.AddComboItem(ref mlassComboBox, "2", "간부");
                combCt.AddComboItem(ref mlassComboBox, "3", "관리자");
                combCt.AddComboItem(ref mlassComboBox, "4", "최고관리자");
                combCt.SelectComboBox(ref mlassComboBox, "1");
                for(int i = 2012; i <  System.DateTime.Now.Year+10; i++)
                {
                    combCt.AddComboItem(ref comboBoxYear, i.ToString(), i.ToString());
                }
                //날짜 초기화
                for (int i = 1; i < 13; i++)
                {
                    string nowMonth = i.ToString();
                    if (nowMonth.Length < 2) nowMonth = "0" + nowMonth;
                    combCt.AddComboItem(ref comboBoxMonth, i.ToString(), nowMonth);
                }
                DateTime today = DateTime.Today;
                DateTime last_day = today.AddMonths(1).AddDays(0 - today.Day);
                for (int i = 1; i <= last_day.Day; i++)
                {
                    string nowDay = i.ToString();
                    if (nowDay.Length < 2) nowDay = "0" + nowDay;
                    combCt.AddComboItem(ref comboBoxDay, i.ToString(), nowDay);
                }
                combCt.SelectComboBox(ref comboBoxDay, System.DateTime.Now.Day.ToString());
                combCt.SelectComboBox(ref comboBoxMonth, System.DateTime.Now.Month.ToString());
                combCt.SelectComboBox(ref comboBoxYear, System.DateTime.Now.Year.ToString());
            }
            buttonCompanyNew_Click(sender, e);
            buttonCardNew_Click(sender, e);
        }

        // 바로가기 생성 함수~

        private void CheckForShortcut()
        {
            try
            {
                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
                    if (ad.IsFirstRun)
                    {
                        string desktoPath = string.Empty;
                        desktoPath = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "\\", "식당회원관리", ".appref-ms");
                        string shortcutName = string.Empty;
                        shortcutName = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), @"\Programs\", "\\", "KIMJH", "\\", "식당회원관리", ".appref-ms");
                        System.IO.File.Copy(shortcutName, desktoPath, true);
                    }
                }
            }
            catch
            {

            }
        }
        
        private void 환경설정CToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frm2 = new Form2();
            if (frm2.ShowDialog() == DialogResult.OK)
            {

            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
            }
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (serialPort1.IsOpen) this.Invoke(new EventHandler(ReadSerialData));  
        }

        private void ReadSerialData(object sender, EventArgs e)
        {
            int iRecSize = serialPort1.BytesToRead; // 수신된 데이터 갯수
            string strRxData;

            if (iRecSize != 0) // 수신된 데이터의 수가 0이 아닐때만 처리하자
            {
                strRxData = "";
                byte[] buff = new byte[iRecSize];

                serialPort1.Read(buff, 0, iRecSize);
                for (int iTemp = 0; iTemp < iRecSize; iTemp++)
                    foreach (byte bData in buff)
                    {
                        if (RecvType == "Hex")
                            strRxData += " " + buff[iTemp].ToString("X2");
                        else
                            strRxData += Convert.ToInt32(buff[iTemp]);
                    }
                DataProcessing(strRxData);
            }
            temp++;
            if (temp > 0)
            {
                Thread.Sleep(300);
                if (tbDataRecv.Text.Length > 100)
                {
                    setText(textBoxCardread, tbDataRecv.Text.ToString());
                }
                setText(tbDataRecv, "");
                temp = 0;
            }
       }



        delegate void Ctrl_Involk0(Control ctrl, string text);

        public void setText(Control ctrl, string txtValue)
        {
            if (ctrl.InvokeRequired)
            {
                Ctrl_Involk0 CI = new Ctrl_Involk0(setText);
                ctrl.Invoke(CI, ctrl, txtValue);
            }
            else
            {
                ctrl.Text = txtValue;
            }
        }        
 
        delegate void SetTextCallback(string Text);

        private void DataProcessing(string Text)
        {
            if (this.tbDataRecv.InvokeRequired)
            {
                SetTextCallback dp = new SetTextCallback(DataProcessing);
                this.Invoke(dp, new object[] { Text });
            }
            else
            {
                this.tbDataRecv.Text += (Text + " ");
            }
        }

        private void EnableControls(bool value)
        {
            if (value == true)
            {
            }
            else
            {
            }
        }

        private void 연결끊기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            serialPort1.Close();
            toolStripStatusLabel2.Text = "시리얼 포트 닫힘";
        }

 
        private void toolStripMenuItemSerialState_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                toolStripStatusLabel2.Text = "시리얼 포트 닫힘";
                toolStripMenuItemSerialState.CheckState = CheckState.Unchecked;
                toolStripMenuItemSerialState.Text = "연결";
            }
            else
            {
                try
                {
                    serialPort1.Open();
                    toolStripStatusLabel2.Text = "시리얼 포트 오픈";
                    toolStripMenuItemSerialState.CheckState = CheckState.Checked;
                    toolStripMenuItemSerialState.Text = "연결끊기";
                }
                catch
                {
                    MessageBox.Show("해당 포트는 사용 중입니다.");
                    return;
                }
            }
       }
        private void buttonCustomerCardInsert_Click(object sender, EventArgs e)
        {
            textBoxCardID.Text = textBoxCardread.Text.Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace("카드를읽혀주세요", ""); ;
            if (textBoxCardID.Text != "")
            {
                if (textBoxCustomerIdx.Text != "" && textBoxCustomerIdx.Text != "0")
                {
                    //카드 매핑 작업 테이블 확인
                    DataSet1.customer_cardDataTable dt = customer_cardTableAdapter.GetDataByCardID(textBoxCardID.Text);
                    if (dt.Count > 0)
                    {
                        MessageBox.Show("이미 사용중인 카드 입니다. 카드 등록이 실패하였습니다.");
                    }
                    else
                    {
                        DataSet1.cardregistDataTable dt2 = cardregistTableAdapter.GetDataByCardID(textBoxCardID.Text);
                        if (dt2.Count > 0)
                        {
                            dt2[0].use_yn = "Y";
                            dt2[0].delChk = "N";
                            cardregistTableAdapter.Update(dt2);
                        }
                        else
                        {
                            cardregistTableAdapter.Insert(textBoxCardID.Text, System.DateTime.Now, "Y", "N");
                            this.cardregistTableAdapter.FillByDelChk(this.dataSet1.cardregist, "N");
                            cardregistDataGridView.DataSource = this.dataSet1.cardregist;
                        }
                        
                        customer_cardTableAdapter.Insert(Int32.Parse(textBoxCustomerIdx.Text), textBoxCardID.Text, System.DateTime.Now, "Y", "");
                        MessageBox.Show("사용자 카드가 등록되었습니다.");
                        this.customer_cardTableAdapter.FillByCustomerIdx(this.dataSet1.customer_card, Int32.Parse(textBoxCustomerIdx.Text));
                        dataGridView2.DataSource = this.dataSet1.customer_card;
                    }
                }
                else
                {                    
                    tabPageCard.Focus();
                    buttonCardInsert_Click(sender, e);
                }
            }
            else
            {
                MessageBox.Show("등록할 카드를 리더기에 읽혀 주세요!");
            }

        }

        private void buttonInsert_Click(object sender, EventArgs e)
        {
            Int32 company_idx =  Int32.Parse(combCt.GetComboKey(ref comboBoxConame));
            textBoxCardID.Text = textBoxCardread.Text.Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace("카드를읽혀주세요", ""); ;
            if(textBoxCardID.Text !="")
            {
                 DataSet1.cardregistDataTable dt = cardregistTableAdapter.GetDataByCardID(textBoxCardID.Text);
                 if (dt.Count > 0)
                 {
                     dt[0].use_yn = "Y";
                     dt[0].delChk = "N";
                     cardregistTableAdapter.Update(dt);
                 }
                 else
                 {
                     cardregistTableAdapter.Insert(textBoxCardID.Text, System.DateTime.Now, "Y", "N");
                     this.cardregistTableAdapter.FillByDelChk(this.dataSet1.cardregist, "N");
                     cardregistDataGridView.DataSource = this.dataSet1.cardregist;
                 }
            }
            int? tempIdx = 0;
            customerTableAdapter.usp_customer_insert(ref tempIdx, textBoxCname.Text, combCt.GetComboText(ref comboBoxConame).ToString(), maskedTextBoxMobile.Text, maskedTextBoxTel.Text, numericUpDownNasun.Value.ToString(), textBoxAltername.Text, textBoxEmail.Text, textBoxRemarks.Text, textBoxCardID.Text, managerID, "N", company_idx);
            int newIdx = (int)tempIdx;
            textBoxCustomerIdx.Text = newIdx.ToString();
            if (textBoxCardID.Text != "")
            {
                //카드 매핑 작업 테이블 확인
                DataSet1.customer_cardDataTable dt = customer_cardTableAdapter.GetDataByCardID(textBoxCardID.Text);
                if (dt.Count > 0)
                {
                    MessageBox.Show("이미 사용중인 카드 입니다. 카드 등록이 실패하였습니다.");
                }
                else
                {
                    customer_cardTableAdapter.Insert(newIdx, textBoxCardID.Text, System.DateTime.Now, "Y", "");
                }                
            }
            textBoxCardread.Text = "";
            tbDataRecv.Text = "";
            buttonInsert.Enabled = false;
            buttonUpdate.Enabled = true;
            buttonDelete.Enabled = true;
            MessageBox.Show("고객이 등록되었습니다.");
            this.customerTableAdapter.FillByDelchk(this.dataSet1.customer, "N");
            dataGridView1.DataSource = this.dataSet1.customer;
            this.customer_cardTableAdapter.FillByCustomerIdx(this.dataSet1.customer_card, newIdx);
            dataGridView2.DataSource = this.dataSet1.customer_card;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            textBoxCardread.Text = "";
            tbDataRecv.Text = "";
            textBoxCname.ResetText();
            comboBoxConame.ResetText();
            maskedTextBoxMobile.ResetText();
            maskedTextBoxTel.ResetText();
            numericUpDownNasun.ResetText();
            textBoxAltername.ResetText();
            textBoxEmail.ResetText();
            textBoxRemarks.ResetText();
            textBoxCardID.ResetText();
        }

        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            if (textBoxCustomerIdx.Text != "" && textBoxCustomerIdx.Text != "0")
            {
                Int32 company_idx = Int32.Parse(combCt.GetComboKey(ref comboBoxConame));

                DataSet1.customerDataTable dt = customerTableAdapter.GetDataByIdx(Int32.Parse(textBoxCustomerIdx.Text));
                if (dt.Count > 0)
                {
                    dt[0].mdate = System.DateTime.Now;
                    dt[0].cname = textBoxCname.Text;
                    dt[0].company = combCt.GetComboText(ref comboBoxConame);
                    dt[0].company_idx = company_idx;
                    dt[0].email = textBoxEmail.Text;
                    dt[0].remarks = textBoxRemarks.Text;
                    dt[0].altername = textBoxAltername.Text;
                }
                customerTableAdapter.Update(dt);
                this.customer_cardTableAdapter.FillByCustomerIdx(this.dataSet1.customer_card, Int32.Parse(textBoxCustomerIdx.Text));
            }
            else
            {
                MessageBox.Show("수정할 데이터를 선택하세요");
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (textBoxCustomerIdx.Text != "" && textBoxCustomerIdx.Text != "0" && MessageBox.Show("고객을 삭제하시겠습니까?", "예 아니오", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                this.DialogResult = DialogResult.Abort;
                customerTableAdapter.UpdateDelChkByIdx("Y", Int32.Parse(textBoxCustomerIdx.Text));
                MessageBox.Show("고객이 삭제되었습니다.");
                buttonNew_Click(sender, e);
                this.customerTableAdapter.FillByDelchk(this.dataSet1.customer, "N");
                dataGridView1.DataSource = this.dataSet1.customer;
            }
            else
            {
                MessageBox.Show("삭제할 데이터를 선택하세요");
            }
        }

        private void buttonNew_Click(object sender, EventArgs e)
        {
            textBoxCustomerIdx.Text = "";
            buttonCancel_Click(sender, e);
            buttonInsert.Enabled = true;
            buttonUpdate.Enabled = false;
            buttonDelete.Enabled = false;
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Int32 selectedRowCount =
                 dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);
            if (selectedRowCount > 0)
            {
                for (int i = 0; i < selectedRowCount; i++)
                {
                    textBoxCustomerIdx.Text = dataGridView1.SelectedRows[i].Cells[0].Value.ToString();
                    textBoxCname.Text = dataGridView1.SelectedRows[i].Cells[1].Value.ToString();
                    combCt.SelectComboBox(ref comboBoxConame, dataGridView1.SelectedRows[i].Cells[13].Value.ToString());
                    maskedTextBoxMobile.Text = dataGridView1.SelectedRows[i].Cells[3].Value.ToString();
                    maskedTextBoxTel.Text = dataGridView1.SelectedRows[i].Cells[4].Value.ToString();
                    numericUpDownNasun.Value = Int32.Parse(dataGridView1.SelectedRows[i].Cells[5].Value.ToString());
                    textBoxAltername.Text = dataGridView1.SelectedRows[i].Cells[6].Value.ToString();
                    textBoxEmail.Text = dataGridView1.SelectedRows[i].Cells[7].Value.ToString();
                    textBoxRemarks.Text = dataGridView1.SelectedRows[i].Cells[8].Value.ToString();
                    textBoxCardID.Text = dataGridView1.SelectedRows[i].Cells[9].Value.ToString();
                    wdateDateTimePicker.Value = Convert.ToDateTime(dataGridView1.SelectedRows[i].Cells[10].Value.ToString());
                }
                buttonInsert.Enabled = false;
                buttonUpdate.Enabled = true;
                buttonDelete.Enabled = true;
                customer_cardTableAdapter.FillByCustomerIdx(this.dataSet1.customer_card, Int32.Parse(textBoxCustomerIdx.Text));
                dataGridView2.DataSource = this.dataSet1.customer_card;
            }

        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            this.dataGridView1.Columns[0].HeaderText = "인덱스";
            this.dataGridView1.Columns[1].HeaderText = "성명";
            this.dataGridView1.Columns[2].HeaderText = "소속회사";
            this.dataGridView1.Columns[3].HeaderText = "이동전화";
            this.dataGridView1.Columns[4].HeaderText = "전화번호";
            this.dataGridView1.Columns[5].HeaderText = "내선번호";
            this.dataGridView1.Columns[6].HeaderText = "별칭";
            this.dataGridView1.Columns[7].HeaderText = "이메일";
            this.dataGridView1.Columns[8].HeaderText = "비고";
            this.dataGridView1.Columns[9].HeaderText = "카드아이디";
            this.dataGridView1.Columns[10].HeaderText = "등록일";
            this.dataGridView1.Columns[11].HeaderText = "수정일";
            this.dataGridView1.Columns[12].HeaderText = "등록자";
            this.dataGridView1.Columns[13].HeaderText = "삭제키";         
            
            this.dataGridView1.Columns[0].Visible = false;  //[idx]         
            this.dataGridView1.Columns[1].Visible = true;   //[cname]       
            this.dataGridView1.Columns[2].Visible = true;  //[company]     
            this.dataGridView1.Columns[3].Visible = false;  //[mobilenum]   
            this.dataGridView1.Columns[4].Visible = false;  //[telnum]      
            this.dataGridView1.Columns[5].Visible = false;  //[nasunnum]    
            this.dataGridView1.Columns[6].Visible = false;  //[altername]   
            this.dataGridView1.Columns[7].Visible = false;  //[email]       
            this.dataGridView1.Columns[8].Visible = false;  //[remarks]     
            this.dataGridView1.Columns[9].Visible = false;  //[baseCardId]  
            this.dataGridView1.Columns[10].Visible = false; //[wdate]       
            this.dataGridView1.Columns[11].Visible = false; //[mdate]       
            this.dataGridView1.Columns[12].Visible = false; //[wid]         
            this.dataGridView1.Columns[13].Visible = false; //[delChk] 
            this.dataGridView1.Columns[14].Visible = false; //[delChk] 
            this.dataGridView1.Columns[1].Width = 60; //"cname";
            this.dataGridView1.Columns[2].Width = 80; //"company";

        }

        private void buttonCompanyInsert_Click(object sender, EventArgs e)
        {
            int newIdx = companyTableAdapter.Insert(conameTextBox.Text, telnumTextBox.Text, telnum2TextBox.Text, managerTextBox.Text, manager2TextBox.Text, remarksTextBox.Text, System.DateTime.Now, null, "N");
            buttonCompanyInsert.Enabled = false;
            buttonCompanyUpdate.Enabled = true;
            buttonCompanyDelete.Enabled = true;
            MessageBox.Show("업체가 등록되었습니다.");
            idxTextBox.Text = newIdx.ToString();
            this.companyTableAdapter.FillByDelChk(this.dataSet1.company, "N");
            companyDataGridView.DataSource = this.dataSet1.company;
        }

        private void buttonCompanyCancel_Click(object sender, EventArgs e)
        {
            conameTextBox.ResetText();
            telnumTextBox.ResetText();
            telnum2TextBox.ResetText();
            manager2TextBox.ResetText();
            managerTextBox.ResetText();
            remarksTextBox.ResetText();
        }

        private void buttonCompanyUpdate_Click(object sender, EventArgs e)
        {
            if (idxTextBox.Text != "" && idxTextBox.Text != "0")
            {
                DataSet1.companyDataTable dt = companyTableAdapter.GetDataByIdx(Int32.Parse(idxTextBox.Text));
                if (dt.Count > 0)
                {
                    dt[0].mdate = System.DateTime.Now;
                    dt[0].coname = conameTextBox.Text;
                    dt[0].telnum = telnumTextBox.Text;
                    dt[0].telnum2 = telnum2TextBox.Text;
                    dt[0].manager = managerTextBox.Text;
                    dt[0].manager2 = manager2TextBox.Text;
                    dt[0].remarks = remarksTextBox.Text;
                }
                companyTableAdapter.Update(dt);
            }
            else
            {
                MessageBox.Show("수정할 데이터를 선택하세요");
            }

        }

        private void buttonCompanyDel_Click(object sender, EventArgs e)
        {
            if (idxTextBox.Text != "" && idxTextBox.Text != "0" && MessageBox.Show("업체를 삭제하시겠습니까?", "예 아니오", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                this.DialogResult = DialogResult.Abort;
                companyTableAdapter.UpdateDelChkByIdx("Y", Int32.Parse(idxTextBox.Text));
                MessageBox.Show("업체가 삭제되었습니다.");
                buttonCompanyNew_Click(sender, e);
                this.companyTableAdapter.FillByDelChk(this.dataSet1.company, "N");
                companyDataGridView.DataSource = this.dataSet1.company;
            }
            else
            {
                MessageBox.Show("삭제할 데이터를 선택하세요");
            }
 
        }

        private void buttonCompanyNew_Click(object sender, EventArgs e)
        {
            idxTextBox.Text = "";
            buttonCompanyCancel_Click(sender, e);
            buttonCompanyInsert.Enabled = true;
            buttonCompanyUpdate.Enabled = false;
            buttonCompanyDelete.Enabled = false; 
        }

        private void companyDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Int32 selectedRowCount =
                 companyDataGridView.Rows.GetRowCount(DataGridViewElementStates.Selected);
            if (selectedRowCount > 0)
            {
                 for (int i = 0; i < selectedRowCount; i++)
                {
                    idxTextBox.Text = companyDataGridView.SelectedRows[i].Cells[0].Value.ToString();                    
                    conameTextBox.Text = companyDataGridView.SelectedRows[i].Cells[1].Value.ToString();
                    telnumTextBox.Text = companyDataGridView.SelectedRows[i].Cells[2].Value.ToString();
                    telnum2TextBox.Text = companyDataGridView.SelectedRows[i].Cells[3].Value.ToString();
                    managerTextBox.Text = companyDataGridView.SelectedRows[i].Cells[4].Value.ToString();
                    manager2TextBox.Text = companyDataGridView.SelectedRows[i].Cells[5].Value.ToString();
                    remarksTextBox.Text = companyDataGridView.SelectedRows[i].Cells[6].Value.ToString();
                    wdateDateTimePicker.Value = Convert.ToDateTime(companyDataGridView.SelectedRows[i].Cells[7].Value.ToString());
                }
                buttonCompanyInsert.Enabled = false;
                buttonCompanyUpdate.Enabled = true;
                buttonCompanyDelete.Enabled = true;
                DataSet1.customerDataTable cdt = new DataSet1.customerDataTable();
                customerTableAdapter.FillByCompanyIdx(cdt, Int32.Parse(idxTextBox.Text));
                this.customerDataGridView.DataSource = cdt;

            }
        }

        private void companyDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            this.companyDataGridView.Columns[0].HeaderText = "인덱스";
            this.companyDataGridView.Columns[1].HeaderText = "업체명";
            this.companyDataGridView.Columns[2].HeaderText = "전화번호";
            this.companyDataGridView.Columns[3].HeaderText = "전화번호2";
            this.companyDataGridView.Columns[4].HeaderText = "담당자";
            this.companyDataGridView.Columns[5].HeaderText = "담당자2";
            this.companyDataGridView.Columns[6].HeaderText = "비고";
            this.companyDataGridView.Columns[7].HeaderText = "등록일";
            this.companyDataGridView.Columns[8].HeaderText = "수정일";
            this.companyDataGridView.Columns[9].HeaderText = "삭제키";

            this.companyDataGridView.Columns[0].Visible = false;  //[idx]     
            this.companyDataGridView.Columns[1].Visible = true;   //[coname]  
            this.companyDataGridView.Columns[2].Visible = false;  //[telnum]  
            this.companyDataGridView.Columns[3].Visible = false;  //[telnum2] 
            this.companyDataGridView.Columns[4].Visible = true;  //[manager] 
            this.companyDataGridView.Columns[5].Visible = false;  //[manager2]
            this.companyDataGridView.Columns[6].Visible = false;  //[remarks] 
            this.companyDataGridView.Columns[7].Visible = false;  //[wdate]   
            this.companyDataGridView.Columns[8].Visible = false;  //[mdate]   
            this.companyDataGridView.Columns[9].Visible = false;  //[delChk]              
            this.dataGridView1.Columns[1].Width = 60; //"cname";
            this.dataGridView1.Columns[2].Width = 80; //"company";
        }

 
        private void customerDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void customerDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            this.customerDataGridView.Columns[0].HeaderText = "인덱스";
            this.customerDataGridView.Columns[1].HeaderText = "성명";
            this.customerDataGridView.Columns[2].HeaderText = "소속회사";
            this.customerDataGridView.Columns[3].HeaderText = "이동전화";
            this.customerDataGridView.Columns[4].HeaderText = "전화번호";
            this.customerDataGridView.Columns[5].HeaderText = "내선번호";
            this.customerDataGridView.Columns[6].HeaderText = "별칭";
            this.customerDataGridView.Columns[7].HeaderText = "이메일";
            this.customerDataGridView.Columns[8].HeaderText = "비고";
            this.customerDataGridView.Columns[9].HeaderText = "카드아이디";
            this.customerDataGridView.Columns[10].HeaderText = "등록일";
            this.customerDataGridView.Columns[11].HeaderText = "수정일";
            this.customerDataGridView.Columns[12].HeaderText = "등록자";
            this.customerDataGridView.Columns[13].HeaderText = "삭제키";

            this.customerDataGridView.Columns[0].Visible = false;  //[idx]         
            this.customerDataGridView.Columns[1].Visible = true;   //[cname]       
            this.customerDataGridView.Columns[2].Visible = true;  //[company]     
            this.customerDataGridView.Columns[3].Visible = false;  //[mobilenum]   
            this.customerDataGridView.Columns[4].Visible = false;  //[telnum]      
            this.customerDataGridView.Columns[5].Visible = false;  //[nasunnum]    
            this.customerDataGridView.Columns[6].Visible = false;  //[altername]   
            this.customerDataGridView.Columns[7].Visible = false;  //[email]       
            this.customerDataGridView.Columns[8].Visible = false;  //[remarks]     
            this.customerDataGridView.Columns[9].Visible = false;  //[baseCardId]  
            this.customerDataGridView.Columns[10].Visible = false; //[wdate]       
            this.customerDataGridView.Columns[11].Visible = false; //[mdate]       
            this.customerDataGridView.Columns[12].Visible = false; //[wid]         
            this.customerDataGridView.Columns[13].Visible = false; //[delChk] 
            this.customerDataGridView.Columns[14].Visible = false; //[company_idx] 
            this.customerDataGridView.Columns[1].Width = 60; //"cname";
            this.customerDataGridView.Columns[2].Width = 80; //"company";
        }

        private void salesDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            this.salesDataGridView.Columns[0].HeaderText = "인덱스";
            this.salesDataGridView.Columns[1].HeaderText = "고객명";
            this.salesDataGridView.Columns[2].HeaderText = "고객번호";
            this.salesDataGridView.Columns[3].HeaderText = "카드아이디";
            this.salesDataGridView.Columns[4].HeaderText = "상품번호";
            this.salesDataGridView.Columns[5].HeaderText = "상품이름";
            this.salesDataGridView.Columns[6].HeaderText = "가격";
            this.salesDataGridView.Columns[7].HeaderText = "등록일";
            this.salesDataGridView.Columns[8].HeaderText = "수정일";
            this.salesDataGridView.Columns[9].HeaderText = "삭제키";
            this.salesDataGridView.Columns[10].HeaderText = "비고";

            this.salesDataGridView.Columns[0].Visible = false;  //[idx]         
            this.salesDataGridView.Columns[1].Visible = true;   //[cname]       
            this.salesDataGridView.Columns[2].Visible = false;   //[customer_idx]
            this.salesDataGridView.Columns[3].Visible = false;  //[cardID]      
            this.salesDataGridView.Columns[4].Visible = false;  //[product_idx] 
            this.salesDataGridView.Columns[5].Visible = true;  //[product_name]
            this.salesDataGridView.Columns[6].Visible = true;  //[price]       
            this.salesDataGridView.Columns[7].Visible = true;  //[wdate]       
            this.salesDataGridView.Columns[8].Visible = false;  //[mdate]       
            this.salesDataGridView.Columns[9].Visible = false;  //[delChk]      
            this.salesDataGridView.Columns[10].Visible = true; //[remarks]     
            this.salesDataGridView.Columns[1].Width = 100; //"cname";
            this.salesDataGridView.Columns[2].Width = 80; //"company";
        }

        private void dataGridView2_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            this.dataGridView2.Columns[0].HeaderText = "고객고유번호";
            this.dataGridView2.Columns[1].HeaderText = "카드아이디";
            this.dataGridView2.Columns[2].HeaderText = "등록일";
            this.dataGridView2.Columns[3].HeaderText = "사용여부";

            this.dataGridView2.Columns[0].Visible = true;  //[idx]         
            this.dataGridView2.Columns[1].Visible = true;   //[cname]       
            this.dataGridView2.Columns[2].Visible = true;   //[customer_idx]
            this.dataGridView2.Columns[3].Visible = true;  //[cardID] 
            this.dataGridView2.Columns[1].Width = 180; //"cname";
            this.dataGridView2.Columns[2].Width = 80; //"company";

        }

        private void productDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            this.productDataGridView.Columns[0].HeaderText = "인덱스";
            this.productDataGridView.Columns[1].HeaderText = "상품명";
            this.productDataGridView.Columns[2].HeaderText = "상품코드";
            this.productDataGridView.Columns[3].HeaderText = "별칭";
            this.productDataGridView.Columns[4].HeaderText = "가격";
            this.productDataGridView.Columns[5].HeaderText = "등록일";
            this.productDataGridView.Columns[6].HeaderText = "수정일";
            this.productDataGridView.Columns[7].HeaderText = "판매유무";
            this.productDataGridView.Columns[8].HeaderText = "삭제키";
            this.productDataGridView.Columns[9].HeaderText = "상품정보";
            this.productDataGridView.Columns[10].HeaderText = "비고";

            this.productDataGridView.Columns[0].Visible = false;  //[idx]      
            this.productDataGridView.Columns[1].Visible = true;   //[pname]    
            this.productDataGridView.Columns[2].Visible = false;  //[pcode]    
            this.productDataGridView.Columns[3].Visible = true;  //[altername]
            this.productDataGridView.Columns[4].Visible = true;  //[price]    
            this.productDataGridView.Columns[5].Visible = true;  //[wdate]    
            this.productDataGridView.Columns[6].Visible = false;  //[mdate]    
            this.productDataGridView.Columns[7].Visible = true;  //[use_yn]   
            this.productDataGridView.Columns[8].Visible = false;  //[delChk]   
            this.productDataGridView.Columns[9].Visible = true;  //[info]     
            this.productDataGridView.Columns[10].Visible = true; //[remarks]  
            this.productDataGridView.Columns[1].Width = 120; //"cname";
            this.productDataGridView.Columns[2].Width = 80; //"company";
        }

        private void buttonProductInsert_Click(object sender, EventArgs e)
        {
            int newIdx = productTableAdapter.Insert(pnameTextBox.Text,pcodeTextBox.Text,alternameTextBox.Text, priceNumericUpDown.Value, System.DateTime.Now, null, "Y", "N", infoTextBox.Text, remarksTextBox1.Text);
            buttonProductInsert.Enabled = false;
            buttonProductUpdate.Enabled = true;
            buttonProductDelete.Enabled = true;
            MessageBox.Show("상품이 등록되었습니다.");
            idxTextBox1.Text = newIdx.ToString();
            this.productTableAdapter.FillByDelChk(this.dataSet1.product, "N");
            productDataGridView.DataSource = this.dataSet1.product;
        }

        private void buttonProductCancel_Click(object sender, EventArgs e)
        {
            pnameTextBox.ResetText();
            pcodeTextBox.ResetText();
            alternameTextBox.ResetText();
            priceNumericUpDown.ResetText();
            infoTextBox.ResetText();
            remarksTextBox1.ResetText();
        }

        private void buttonProductUpdate_Click(object sender, EventArgs e)
        {
            if (idxTextBox1.Text != "" && idxTextBox1.Text != "0")
            {
                DataSet1.productDataTable dt = productTableAdapter.GetDataByIdx(Int32.Parse(idxTextBox.Text));
                if (dt.Count > 0)
                {
                    dt[0].mdate = System.DateTime.Now;
                    dt[0].pname = pnameTextBox.Text;
                    dt[0].altername = alternameTextBox.Text;
                    dt[0].price = priceNumericUpDown.Value;
                    dt[0].info = infoTextBox.Text;
                    dt[0].pcode = pcodeTextBox.Text;
                    dt[0].remarks = remarksTextBox1.Text;
                    string use_yn = "Y";
                    if (use_ynRadioButtonN.Checked == true) use_yn = "N";
                    dt[0].use_yn = use_yn;

                }
                productTableAdapter.Update(dt);
            }
            else
            {
                MessageBox.Show("수정할 데이터를 선택하세요");
            }

        }

        private void buttonProductDelete_Click(object sender, EventArgs e)
        {
            if (idxTextBox1.Text != "" && idxTextBox1.Text != "0" && MessageBox.Show("상품을 삭제하시겠습니까?", "예 아니오", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                this.DialogResult = DialogResult.Abort;
                productTableAdapter.UpdateDelChkByIdx("Y", Int32.Parse(idxTextBox1.Text));
                MessageBox.Show("상품이 삭제되었습니다.");
                buttonProductNew_Click(sender, e);
                this.productTableAdapter.FillByDelChk(this.dataSet1.product, "N");
                productDataGridView.DataSource = this.dataSet1.product;
            }
            else
            {
                MessageBox.Show("삭제할 데이터를 선택하세요");
            }

        }

        private void buttonProductNew_Click(object sender, EventArgs e)
        {
            idxTextBox1.Text = "";
            buttonProductCancel_Click(sender, e);
            buttonProductInsert.Enabled = true;
            buttonProductUpdate.Enabled = false;
            buttonProductDelete.Enabled = false;
        }

        private void productDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Int32 selectedRowCount =
                 productDataGridView.Rows.GetRowCount(DataGridViewElementStates.Selected);
            if (selectedRowCount > 0)
            {
                for (int i = 0; i < selectedRowCount; i++)
                {
                    idxTextBox1.Text = productDataGridView.SelectedRows[i].Cells[0].Value.ToString();
                    pnameTextBox.Text = productDataGridView.SelectedRows[i].Cells[1].Value.ToString();
                    pcodeTextBox.Text = productDataGridView.SelectedRows[i].Cells[2].Value.ToString();
                    alternameTextBox.Text = productDataGridView.SelectedRows[i].Cells[3].Value.ToString();
                    priceNumericUpDown.Value = Int32.Parse(productDataGridView.SelectedRows[i].Cells[4].Value.ToString());
                    wdateDateTimePicker1.Value = Convert.ToDateTime(productDataGridView.SelectedRows[i].Cells[5].Value.ToString());
                    string use_yn = productDataGridView.SelectedRows[i].Cells[7].Value.ToString();
                    if (use_yn == "Y")
                    {
                        use_ynRadioButtonY.Checked = true;
                    }
                    else
                    {
                        use_ynRadioButtonN.Checked = true;
                    }
                    infoTextBox.Text = productDataGridView.SelectedRows[i].Cells[9].Value.ToString();
                    remarksTextBox1.Text = productDataGridView.SelectedRows[i].Cells[10].Value.ToString();
                }
                buttonProductInsert.Enabled = false;
                buttonProductUpdate.Enabled = true;
                buttonProductDelete.Enabled = true;
            }

        }

        private void cardregistDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {

            this.cardregistDataGridView.Columns[0].HeaderText = "인덱스";
            this.cardregistDataGridView.Columns[1].HeaderText = "카드아이디";
            this.cardregistDataGridView.Columns[2].HeaderText = "등록일";
            this.cardregistDataGridView.Columns[3].HeaderText = "사용여부";
            this.cardregistDataGridView.Columns[4].HeaderText = "삭제키";

            this.cardregistDataGridView.Columns[0].Visible = false;  //[idx]    
            this.cardregistDataGridView.Columns[1].Visible = true;   //[cardID] 
            this.cardregistDataGridView.Columns[2].Visible = true;   //[wdate]  
            this.cardregistDataGridView.Columns[3].Visible = true;  //[use_yn] 
            this.cardregistDataGridView.Columns[4].Visible = false;  //[delChk] 
            this.cardregistDataGridView.Columns[1].Width = 300; //"cname";
            this.cardregistDataGridView.Columns[2].Width = 120; //"company";
        }

        private void cardregistDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Int32 selectedRowCount =
                 cardregistDataGridView.Rows.GetRowCount(DataGridViewElementStates.Selected);
            if (selectedRowCount > 0)
            {
                for (int i = 0; i < selectedRowCount; i++)
                {
                    idxTextBox2.Text = cardregistDataGridView.SelectedRows[i].Cells[0].Value.ToString();
                    cardIDTextBox.Text = cardregistDataGridView.SelectedRows[i].Cells[1].Value.ToString();
                    wdateDateTimePicker2.Value = Convert.ToDateTime(cardregistDataGridView.SelectedRows[i].Cells[2].Value.ToString());
                    string use_yn = cardregistDataGridView.SelectedRows[i].Cells[3].Value.ToString();
                    if (use_yn == "Y")
                    {
                        use_ynRadioButtonCardY.Checked = true;
                    }
                    else
                    {
                        use_ynRadioButtonCardN.Checked = true;
                    }
                }
                buttonCardInsert.Enabled = false;
                buttonCardUpdate.Enabled = true;
                buttonCardDelete.Enabled = true;
            }

        }

        private void buttonCardInsert_Click(object sender, EventArgs e)
        {
            cardIDTextBox.Text = textBoxCardread.Text.Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace("카드를읽혀주세요", ""); ;
            if (cardIDTextBox.Text != "")
            {
                DataSet1.cardregistDataTable crdt = cardregistTableAdapter.GetDataByCardID(cardIDTextBox.Text);
                if (crdt.Rows.Count > 0)
                {
                    MessageBox.Show("이미 등록되어있는 카드입니다.");
                }
                else
                {
                    int newIdx = cardregistTableAdapter.Insert(cardIDTextBox.Text, System.DateTime.Now, "Y", "N");
                    buttonCardInsert.Enabled = false;
                    buttonCardUpdate.Enabled = true;
                    buttonCardDelete.Enabled = true;
                    MessageBox.Show("카드가 등록되었습니다.");
                    idxTextBox2.Text = newIdx.ToString();
                    this.cardregistTableAdapter.FillByDelChk(this.dataSet1.cardregist, "N");
                    cardregistDataGridView.DataSource = this.dataSet1.cardregist;
                }
            }
            else
            {
                MessageBox.Show("카드를 리더기에 읽어 주세요");
            }
        }

        private void buttonCardCancel_Click(object sender, EventArgs e)
        {
            cardIDTextBox.ResetText();
        }

        private void buttonCardUpdate_Click(object sender, EventArgs e)
        {
            if (idxTextBox2.Text != "" && idxTextBox2.Text != "0")
            {
                DataSet1.cardregistDataTable dt = cardregistTableAdapter.GetDataByIdx(Int32.Parse(idxTextBox2.Text));
                if (dt.Count > 0)
                {
                    string use_yn = "Y";
                    if (use_ynRadioButtonCardN.Checked == true) use_yn = "N";
                    dt[0].use_yn = use_yn;
                }
                cardregistTableAdapter.Update(dt);
            }
            else
            {
                MessageBox.Show("수정할 데이터를 선택하세요");
            }

        }

        private void buttonCardDelete_Click(object sender, EventArgs e)
        {
            if (idxTextBox2.Text != "" && idxTextBox2.Text != "0" && MessageBox.Show("카드를 삭제하시겠습니까?", "예 아니오", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                this.DialogResult = DialogResult.Abort;
                cardregistTableAdapter.UpdateDelChkByIdx("Y", Int32.Parse(idxTextBox2.Text));
                MessageBox.Show("카드가 삭제되었습니다.");
                buttonCardNew_Click(sender, e);
                this.cardregistTableAdapter.FillByDelChk(this.dataSet1.cardregist, "N");
                cardregistDataGridView.DataSource = this.dataSet1.cardregist;
            }
            else
            {
                MessageBox.Show("삭제할 데이터를 선택하세요");
            }

        }

        private void buttonCardNew_Click(object sender, EventArgs e)
        {
            idxTextBox2.Text = "";
            buttonCardCancel_Click(sender, e);
            buttonCardInsert.Enabled = true;
            buttonCardUpdate.Enabled = false;
            buttonCardDelete.Enabled = false;
        }

        private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void salesDataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {

        }

        private void salesDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void managerDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Int32 selectedRowCount =
                 managerDataGridView.Rows.GetRowCount(DataGridViewElementStates.Selected);
            if (selectedRowCount > 0)
            {
                for (int i = 0; i < selectedRowCount; i++)
                {
                    idTextBox.Text = managerDataGridView.SelectedRows[i].Cells[0].Value.ToString();
                    mnameTextBox.Text = managerDataGridView.SelectedRows[i].Cells[1].Value.ToString();
                    pwdTextBox.Text = managerDataGridView.SelectedRows[i].Cells[2].Value.ToString();
                    wdateDateTimePicker3.Value = Convert.ToDateTime(managerDataGridView.SelectedRows[i].Cells[3].Value.ToString());
                    loginCntLabel1.Text = managerDataGridView.SelectedRows[i].Cells[5].Value.ToString();
                    lastLogindateDateTimePicker.Text = managerDataGridView.SelectedRows[i].Cells[6].Value.ToString();
                    string use_yn = managerDataGridView.SelectedRows[i].Cells[7].Value.ToString();
                    if (use_yn == "Y")
                    {
                        manageruse_ynRadioButtonY.Checked = true;
                    }
                    else
                    {
                        manageruse_ynRadioButtonN.Checked = true;
                    }
                    combCt.SelectComboBox(ref mlassComboBox, managerDataGridView.SelectedRows[i].Cells[9].Value.ToString());
                }
                buttonManagerInsert.Enabled = false;
                buttonManagerUpdate.Enabled = true;
                buttonManagerDelete.Enabled = true;
            }

        }

        private void managerDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            this.managerDataGridView.Columns[0].HeaderText = "아이디";
            this.managerDataGridView.Columns[1].HeaderText = "직원명";
            this.managerDataGridView.Columns[2].HeaderText = "비밀번호";
            this.managerDataGridView.Columns[3].HeaderText = "등록일";
            this.managerDataGridView.Columns[4].HeaderText = "수정일";
            this.managerDataGridView.Columns[5].HeaderText = "로그인횟수";
            this.managerDataGridView.Columns[6].HeaderText = "마지막로그인";
            this.managerDataGridView.Columns[7].HeaderText = "이용허가";
            this.managerDataGridView.Columns[8].HeaderText = "삭제키";
            this.managerDataGridView.Columns[9].HeaderText = "등급";

            this.managerDataGridView.Columns[0].Visible = true;  //[id]            
            this.managerDataGridView.Columns[1].Visible = true;   //[mname]         
            this.managerDataGridView.Columns[2].Visible = false;  //[pwd]           
            this.managerDataGridView.Columns[3].Visible = true;  //[wdate]         
            this.managerDataGridView.Columns[4].Visible = false;  //[mdate]         
            this.managerDataGridView.Columns[5].Visible = true;  //[loginCnt]      
            this.managerDataGridView.Columns[6].Visible = true;  //[lastLogindate] 
            this.managerDataGridView.Columns[7].Visible = true;  //[use_yn]        
            this.managerDataGridView.Columns[8].Visible = false;  //[delChk]        
            this.managerDataGridView.Columns[9].Visible = true;  //[mlass]         
            this.managerDataGridView.Columns[1].Width = 120; //"id";
            this.managerDataGridView.Columns[2].Width = 120; //"mname";

        }

        private void buttonManagerInsert_Click(object sender, EventArgs e)
        {
            Int32 intClass = Int32.Parse(combCt.GetComboKey(ref mlassComboBox));
                DataSet1.managerDataTable dt = managerTableAdapter.GetDataById(idTextBox.Text);
                if (dt.Count > 0)
                {
                    MessageBox.Show("이미 존재하는 아이디입니다.");
                }
                else
                {
                    managerTableAdapter.Insert(idTextBox.Text, mnameTextBox.Text, pwdTextBox.Text, System.DateTime.Now, null, 0, null, "Y", "N", intClass);
                    buttonManagerInsert.Enabled = false;
                    buttonManagerUpdate.Enabled = true;
                    buttonManagerDelete.Enabled = true;
                    MessageBox.Show("사용자가 등록되었습니다.");
                    this.managerTableAdapter.FillByDelChk(this.dataSet1.manager, "N");
                    managerDataGridView.DataSource = this.dataSet1.manager;
                }
        }

        private void buttonManagerCancel_Click(object sender, EventArgs e)
        {
            idTextBox.ResetText();
            mnameTextBox.ResetText();
            pwdTextBox.ResetText();
        }

        private void buttonManagerUpdate_Click(object sender, EventArgs e)
        {
            if (idTextBox.Text != "" && idTextBox.Text != "0")
            {
                DataSet1.managerDataTable dt = managerTableAdapter.GetDataById(idTextBox.Text);
                if (dt.Count > 0)
                {
                    dt[0].mdate = System.DateTime.Now;
                    dt[0].pwd = pwdTextBox.Text;
                    dt[0].mname = mnameTextBox.Text;
                    Int32 intClass = Int32.Parse(combCt.GetComboKey(ref mlassComboBox));
                    dt[0].mlass = intClass;
                    string use_yn = "Y";
                    if (manageruse_ynRadioButtonN.Checked == true)
                    {
                        use_yn = "N";
                    }
                    dt[0].use_yn = use_yn;
                }
                managerTableAdapter.Update(dt[0]);
            }

        }

        private void buttonManagerDelete_Click(object sender, EventArgs e)
        {
            if (idTextBox.Text != "" && idTextBox.Text != "0" && MessageBox.Show("사용자를 삭제하시겠습니까?", "예 아니오", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                this.DialogResult = DialogResult.Abort;
                managerTableAdapter.UpdateDelChkById("Y", idTextBox.Text);
                MessageBox.Show("사용자가 삭제되었습니다.");
                buttonManagerNew_Click(sender, e);
                this.managerTableAdapter.FillByDelChk(this.dataSet1.manager, "N");
                managerDataGridView.DataSource = this.dataSet1.manager;
            }

        }

        private void buttonManagerNew_Click(object sender, EventArgs e)
        {
            idTextBox.Text = "";
            buttonManagerCancel_Click(sender, e);
            buttonManagerInsert.Enabled = true;
            buttonManagerUpdate.Enabled = false;
            buttonManagerDelete.Enabled = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBoxLoginID.Text == "" || textBoxLoginID.Text.Trim().Length == 0)
            {
                MessageBox.Show("아이디를 입력하세요!");
                textBoxLoginID.Focus();
                return;
            }
            if (textBoxLoginPwd.Text == "" || textBoxLoginPwd.Text.Trim().Length == 0)
            {
                MessageBox.Show("비밀번호를 입력하세요!");
                textBoxLoginPwd.Focus();
                return;
            }
            DataSet1.managerDataTable dt = managerTableAdapter.GetDataById(textBoxLoginID.Text);
            if (dt.Count > 0)
            {
                string pwdPWD = dt[0].pwd;
                managerID = textBoxLoginID.Text;
                managerName = dt[0].mname;
                if (pwdPWD == textBoxLoginPwd.Text.ToString() && dt[0].use_yn == "Y")
                {
                    managerClasss = dt[0].mlass;
                    dt[0].lastLogindate = System.DateTime.Now;
                    dt[0].loginCnt = dt[0].loginCnt + 1;
                    MessageBox.Show(managerName + "님 로그인 하였습니다!\n\n좋은 하루 되세요!!");
                    managerTableAdapter.Update(dt[0]);
                    Form1_Load(sender, e);
                }
                else
                {
                    MessageBox.Show(managerName + "님 비밀번호가 일치하지 않거나 사용중지 중입니다!! \n\n 확인하고 이용하세요!");
                    return;
                }
           }
            else
            {
                MessageBox.Show("아이디가 존재하지 않습니다!! \n\n 확인하고 이용하세요!");
                return;
            }
        }

        private void comboBoxYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            setComboBoxDay();
        }

        private void comboBoxMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            setComboBoxDay();
        }

        private void comboBoxDay_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void setComboBoxDay()
        {
            string CurrentYear = combCt.GetComboText(ref comboBoxYear);
            string CurrentMonth = combCt.GetComboText(ref comboBoxMonth);
            string CurrentDay = combCt.GetComboText(ref comboBoxDay);
            if (CurrentYear != "" && CurrentMonth != "" && CurrentDay != "")
            {
                string dateString = CurrentYear + "-" + CurrentMonth + "-" + CurrentDay;
                DateTime today = new DateTime();
                today = DateTime.ParseExact(dateString, "yyyy-MM-dd", null);
                DateTime last_day = today.AddMonths(1).AddDays(0 - today.Day);
                comboBoxDay.Items.Clear();
                for (int i = 1; i <= last_day.Day; i++)
                {
                    string nowDay = i.ToString();
                    if (nowDay.Length < 2) nowDay = "0" + nowDay;
                    combCt.AddComboItem(ref comboBoxDay, i.ToString(), nowDay);
                }
                combCt.SelectComboBox(ref comboBoxDay, System.DateTime.Now.Day.ToString());
            }
        }

        private void textBoxLoginPwd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                button1_Click(sender, e);
        }

        private void textBoxLoginID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                button1_Click(sender, e);
        }

        private void 종료XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonSaleInsert_Click(object sender, EventArgs e)
        {
             cardIDTextBox1.Text = textBoxCardread.Text.Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace("카드를읽혀주세요","");
            int productidx = 0;
            string customerName = "";
            string productName = "";
            if (cardIDTextBox1.Text != "" && cardIDTextBox1.Text != "카드를읽혀주세요")
            {
                DataSet1.view_customer_cardDataTable vcdt = view_customer_cardTableAdapter.GetDataByCardId(cardIDTextBox1.Text);
                if (vcdt.Rows.Count > 0) //카드가 있음
                {
                    combCt.SelectComboBox(ref comboBoxSalesCname, vcdt[0].customer_idx.ToString());
                    customer_idxTextBox.Text = vcdt[0].customer_idx.ToString();

                    if (vcdt[0].use_yn == "N" && MessageBox.Show("카드가 사용 중지 중입니다. 사용 등록하시겠습니까?", "예 아니오", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        this.DialogResult = DialogResult.Abort;
                        customer_cardTableAdapter.UpdateUseYnByCardId("Y", cardIDTextBox1.Text);
                    }
                }                
                else
                {
                    MessageBox.Show("등록되지 않은 카드입니다!");
                    return;
                }
            }
            else if (customer_idxTextBox.Text.ToString() == "" && MessageBox.Show("고객선택 없이 계속 매출 등록하시겠습니까?", "예 아니오", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                this.DialogResult = DialogResult.Abort;
                customer_idxTextBox.Text = "0";
            }
            else
            {
                return;
            }
            int customerIdx = Int32.Parse(customer_idxTextBox.Text.ToString());
            if(combCt.GetComboKey(ref comboBoxproductName) !="") productidx = Int32.Parse(combCt.GetComboKey(ref comboBoxproductName));
            customerName = combCt.GetComboText(ref comboBoxSalesCname);
            if (customerName == "") customerName = comboBoxSalesCname.Text;
            productName = combCt.GetComboText(ref comboBoxproductName);
            if (productName == "") productName = comboBoxproductName.Text;
            salesTableAdapter.Insert(customerName, customerIdx, cardIDTextBox1.Text, productidx, productName, priceNumericUpDown1.Value, System.DateTime.Now, null, "N", "매출 발생");
            MessageBox.Show("매출이 등록되었습니다!");
            textBoxCardread.Text = "";
            salesTableAdapter.FillByDelChk(this.dataSet1.sales, "N");
            salesDataGridView1.DataSource =  this.dataSet1.sales;
        }

        private void comboBoxproductName_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataSet1.productDataTable dt = productTableAdapter.GetDataByIdx(Int32.Parse(combCt.GetComboKey(ref comboBoxproductName).ToString()));
            if(dt.Rows.Count > 0)
            {
                priceNumericUpDown1.Value = dt[0].price;
            }
        }

        private void buttonSalesNew_Click(object sender, EventArgs e)
        {
            comboBoxSalesCname.ResetText();
            customer_idxTextBox.ResetText();
            comboBoxproductName.ResetText();
            cardIDTextBox1.ResetText();
            priceNumericUpDown1.Value = 0;
            textBoxCardread.Text = "";
            remarksTextBox2.ResetText();
        }

        private void textBoxCardread_TextChanged(object sender, EventArgs e)
        {
            Thread.Sleep(300);
            if (readerSet > 0)
            {
                if (textBoxCardread.Text.Length > 100)
                {
                    if (tabControlProduct.SelectedTab == tabPageSales)
                    {
                        buttonSaleInsert_Click(sender, e);
                    }
                }
            }
            else
            {
                readerTest();
                if (textBoxCardread.Text.Length > 100)
                {
                    prevCardId = textBoxCardread.Text;
                    textBoxCardread.Text = "";
                }
            }
        }
        private void readerTest()
        {
            if (readerSet == 0 && textBoxCardread.Text == prevCardId)
            {
                MessageBox.Show("리더기 테스트 완료!");
                textBoxCardread.Text = "";
                readerSet++;
            }
        } 
    }
}
